package com.suncaper.shop.service;

import com.suncaper.shop.component.Utils;
import com.suncaper.shop.domain.Wish;
import com.suncaper.shop.domain.WishExample;
import com.suncaper.shop.mapper.WishMapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.List;

@Service
public class WishService {


    @Autowired
    private WishMapper wishMapper;

    private WishExample wishExample;

    @Autowired
    private ProductService productService;

    /**
     * 通过用户的uid和pid判断是否添加到愿望清单
     *
     * @param pid
     * @param uid
     */
    public void addToWish(Integer pid, Integer uid) {
        wishExample = new WishExample();
        wishExample.createCriteria().andPidEqualTo(pid).andUidEqualTo(uid);
        List<Wish> wishes = wishMapper.selectByExample(wishExample);
        if (wishes.size() > 0) {
            //如果该用户的愿望清单本身具有该商品，就不再加入
            return;
        }
        Utils utils = new Utils();
        Wish wish = new Wish();
        wish.setPid(pid);
        wish.setUid(uid);
        wish.setWishid(utils.getCode());
        wishMapper.insert(wish);
    }

    /**
     * 通过uid来，获取该用户的所用愿望列表
     *
     * @param uid
     * @return
     */
    public List<Wish> getAllWishList(Integer uid) {
        wishExample = new WishExample();
        wishExample.createCriteria().andUidEqualTo(uid);
        List<Wish> wishList = wishMapper.selectByExample(wishExample);
        if (wishList.size() > 0) {
            for (Wish item : wishList) {
                //通过pid找到对应product,将其封装
                item.setProduct(productService.findByPid(item.getPid()));
            }
            return wishList;
        }
        return null;
    }

    /**
     * 从愿望清单中删除指定的项
     *
     * @param pid
     */
    public void deleteFromWish(Integer pid) {
        wishExample = new WishExample();
        wishExample.createCriteria().andPidEqualTo(pid);
        wishMapper.deleteByExample(wishExample);
    }
}
